<!DOCTYPE html>
<html lang="zh-CN">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>视频上传与处理</title>
    <style>
      .upload-container {
        max-width: 900px;
        margin: 40px auto;
        padding: 30px;
        border: 2px dashed #ccc;
        border-radius: 12px;
        text-align: center;
        transition: all 0.3s ease;
      }
      .upload-container.active {
        border-color: #4285f4;
        background-color: #f8faff;
      }
      .tab-container {
        margin-top: 30px;
        display: flex;
        justify-content: center;
      }
      .tab-btn {
        padding: 12px 25px;
        margin: 0 5px;
        background-color: #f1f1f1;
        border: none;
        border-radius: 6px 6px 0 0;
        cursor: pointer;
        font-size: 16px;
        transition: all 0.2s ease;
      }
      .tab-btn.active {
        background-color: #4285f4;
        color: white;
      }
      .tab-content {
        padding: 25px;
        border: 1px solid #ddd;
        border-radius: 0 0 6px 6px;
        margin-top: -1px;
      }
      .video-preview {
        margin-top: 20px;
        width: 100%;
        max-height: 350px;
        border-radius: 8px;
        box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
      }
      .btn {
        margin: 20px 8px;
        padding: 12px 28px;
        border: none;
        border-radius: 6px;
        cursor: pointer;
        font-size: 16px;
        transition: all 0.2s ease;
        display: inline-flex;
        align-items: center;
      }
      .btn-primary {
        background-color: #4285f4;
        color: white;
      }
      .btn-secondary {
        background-color: #f1f1f1;
        color: #333;
      }
      .btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
      }
      .btn:disabled {
        background-color: #ddd;
        color: #888;
        cursor: not-allowed;
        transform: none;
        box-shadow: none;
      }
      .file-info {
        margin-top: 20px;
        text-align: left;
        padding: 15px;
        background-color: #f5f5f5;
        border-radius: 6px;
      }
      .result-container {
        margin-top: 25px;
      }
      .result-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 15px;
      }
      .result-textarea {
        width: 100%;
        min-height: 150px;
        padding: 15px;
        border: 1px solid #ddd;
        border-radius: 6px;
        background-color: #f9f9f9;
        font-family: monospace;
        font-size: 14px;
        resize: vertical;
        overflow: auto;
      }
      .progress-container {
        margin-top: 20px;
        width: 100%;
        background-color: #ddd;
        border-radius: 5px;
        overflow: hidden;
        display: none;
      }
      .progress-bar {
        width: 0%;
        height: 35px;
        background-color: #4285f4;
        text-align: center;
        line-height: 35px;
        color: white;
        transition: width 0.3s ease;
      }
      .status-message {
        margin-top: 20px;
        padding: 12px;
        border-radius: 6px;
        font-size: 15px;
      }
      .status-success {
        background-color: #d4edda;
        color: #155724;
      }
      .status-error {
        background-color: #f8d7da;
        color: #721c24;
      }
      .status-info {
        background-color: #d1ecf1;
        color: #0c5460;
      }
      .chunk-option {
        margin-top: 20px;
        text-align: left;
        padding: 15px;
        background-color: #f9f9f9;
        border-radius: 6px;
      }
      .chunk-size-selector {
        margin: 10px 0;
        padding: 8px 12px;
        border-radius: 4px;
        border: 1px solid #ddd;
      }
    </style>
  </head>
  <body>
    <div class="upload-container" id="uploadContainer">
      <h3 class="mb-4">拖放视频到这里，或者点击选择文件</h3>
      <input
        type="file"
        id="videoInput"
        accept="video/*"
        style="display: none"
      />
      <button
        class="btn btn-primary"
        onclick="document.getElementById('videoInput').click()"
      >
        <i class="fa fa-upload mr-2"></i>选择视频文件
      </button>

      <div class="video-container">
        <video id="preview" class="video-preview" controls></video>
      </div>

      <div class="file-info" id="fileInfo">
        <p><strong>文件名:</strong> <span id="fileName">-</span></p>
        <p><strong>文件大小:</strong> <span id="fileSize">-</span></p>
        <p><strong>MIME类型:</strong> <span id="fileType">-</span></p>
      </div>

      <div class="tab-container">
        <button class="tab-btn active" onclick="switchTab('base64Tab')">
          Base64编码
        </button>
        <button class="tab-btn" onclick="switchTab('blobTab')">Blob处理</button>
      </div>

      <div id="base64Tab" class="tab-content">
        <button id="base64ConvertBtn" class="btn btn-primary" disabled>
          <i class="fa fa-exchange mr-2"></i>转换为Base64
        </button>

        <div class="progress-container" id="base64ProgressContainer">
          <div class="progress-bar" id="base64ProgressBar">0%</div>
        </div>

        <div class="result-container">
          <div class="result-header">
            <h4>Base64编码结果</h4>
            <button id="base64CopyBtn" class="btn btn-secondary" disabled>
              <i class="fa fa-copy mr-2"></i>复制
            </button>
            <button id="base64DownloadBtn" class="btn btn-secondary" disabled>
              <i class="fa fa-download mr-2"></i>下载
            </button>
          </div>
          <textarea
            id="base64Output"
            class="result-textarea"
            readonly
          ></textarea>
        </div>
      </div>

      <div id="blobTab" class="tab-content" style="display: none">
        <div class="chunk-option">
          <h4>分片大小设置</h4>
          <select id="chunkSizeSelector" class="chunk-size-selector">
            <option value="1">1MB</option>
            <option value="5" selected>5MB</option>
            <option value="10">10MB</option>
            <option value="20">20MB</option>
            <option value="50">50MB</option>
          </select>
          <p class="text-sm text-gray-600">大文件建议使用更大的分片大小</p>
        </div>

        <button id="blobUploadBtn" class="btn btn-primary" disabled>
          <i class="fa fa-cloud-upload mr-2"></i>上传Blob
        </button>

        <div class="progress-container" id="blobProgressContainer">
          <div class="progress-bar" id="blobProgressBar">0%</div>
        </div>

        <div id="blobStatus" class="status-message status-info"></div>

        <div class="result-container">
          <div class="result-header">
            <h4>上传结果</h4>
            <button id="blobUrlCopyBtn" class="btn btn-secondary" disabled>
              <i class="fa fa-copy mr-2"></i>复制URL
            </button>
          </div>
          <textarea id="blobOutput" class="result-textarea" readonly></textarea>
        </div>
      </div>

      <div id="statusMessage" class="status-message"></div>
    </div>
    <script src="../../yl/zh-cn.mjs"></script>
    <script>
      const uploadContainer = document.getElementById("uploadContainer");
      const videoInput = document.getElementById("videoInput");
      const preview = document.getElementById("preview");
      const fileName = document.getElementById("fileName");
      const fileSize = document.getElementById("fileSize");
      const fileType = document.getElementById("fileType");
      const statusMessage = document.getElementById("statusMessage");

      // Base64相关元素
      const base64ConvertBtn = document.getElementById("base64ConvertBtn");
      const base64ProgressContainer = document.getElementById(
        "base64ProgressContainer"
      );
      const base64ProgressBar = document.getElementById("base64ProgressBar");
      const base64Output = document.getElementById("base64Output");
      const base64CopyBtn = document.getElementById("base64CopyBtn");
      const base64DownloadBtn = document.getElementById("base64DownloadBtn");

      // Blob相关元素
      const blobUploadBtn = document.getElementById("blobUploadBtn");
      const blobProgressContainer = document.getElementById(
        "blobProgressContainer"
      );
      const blobProgressBar = document.getElementById("blobProgressBar");
      const blobOutput = document.getElementById("blobOutput");
      const blobUrlCopyBtn = document.getElementById("blobUrlCopyBtn");
      const blobStatus = document.getElementById("blobStatus");
      const chunkSizeSelector = document.getElementById("chunkSizeSelector");

      let selectedFile = null;
      let currentTab = "base64Tab";

      // 拖放事件
      uploadContainer.addEventListener("dragover", (e) => {
        e.preventDefault();
        uploadContainer.classList.add("active");
      });

      uploadContainer.addEventListener("dragleave", () => {
        uploadContainer.classList.remove("active");
      });

      uploadContainer.addEventListener("drop", (e) => {
        e.preventDefault();
        uploadContainer.classList.remove("active");

        if (e.dataTransfer.files.length) {
          const file = e.dataTransfer.files[0];
          handleVideoFile(file);
        }
      });

      // 点击上传
      videoInput.addEventListener("change", () => {
        if (videoInput.files.length) {
          const file = videoInput.files[0];
          handleVideoFile(file);
        }
      });

      // 处理视频文件
      function handleVideoFile(file) {
        resetUI();

        if (file.type.startsWith("video/")) {
          selectedFile = file;
          updateFileInfo(file);

          const videoURL = URL.createObjectURL(file);
          preview.src = videoURL;
          preview.style.display = "block";

          // 启用处理按钮
          base64ConvertBtn.disabled = false;
          blobUploadBtn.disabled = false;

          showStatus("视频已加载，可以选择处理方式", "success");
        } else {
          showStatus("请上传视频文件！", "error");
        }
      }

      // 更新文件信息
      function updateFileInfo(file) {
        fileName.textContent = file.name;
        fileSize.textContent = formatFileSize(file.size);
        fileType.textContent = file.type;
      }

      // 格式化文件大小
      function formatFileSize(bytes) {
        if (bytes === 0) return "0 Bytes";
        const k = 1024;
        const sizes = ["Bytes", "KB", "MB", "GB", "TB"];
        const i = Math.floor(Math.log(bytes) / Math.log(k));
        return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i];
      }

      // 切换选项卡
      function switchTab(tabName) {
        currentTab = tabName;

        // 隐藏所有选项卡
        document.querySelectorAll(".tab-content").forEach((tab) => {
          tab.style.display = "none";
        });

        // 显示选中的选项卡
        document.getElementById(tabName).style.display = "block";

        // 更新选项卡按钮样式
        document.querySelectorAll(".tab-btn").forEach((btn) => {
          btn.classList.remove("active");
        });
        document
          .querySelector(`.tab-btn[onclick="switchTab('${tabName}')"]`)
          .classList.add("active");
      }

      // Base64转换相关
      base64ConvertBtn.addEventListener("click", () => {
        if (!selectedFile) return;

        base64ConvertBtn.disabled = true;
        base64ProgressContainer.style.display = "block";
        showStatus("正在将视频转换为Base64格式...", "success");

        const reader = new FileReader();

        reader.onprogress = (e) => {
          if (e.lengthComputable) {
            const percentComplete = Math.round((e.loaded / e.total) * 100);
            base64ProgressBar.style.width = percentComplete + "%";
            base64ProgressBar.textContent = percentComplete + "%";
          }
        };

        reader.onload = (e) => {
          const base64Result = e.target.result;
          base64Output.value = base64Result;

          base64CopyBtn.disabled = false;
          base64DownloadBtn.disabled = false;

          showStatus("视频已成功转换为Base64格式！", "success");
          base64ProgressContainer.style.display = "none";
        };

        reader.onerror = () => {
          showStatus("转换过程中发生错误，请重试。", "error");
          base64ProgressContainer.style.display = "none";
        };

        reader.readAsDataURL(selectedFile);
      });

      // 复制Base64结果
      base64CopyBtn.addEventListener("click", () => {
        if (!base64Output.value) return;

        base64Output.select();
        document.execCommand("copy");

        showStatus("Base64编码已复制到剪贴板！", "success");

        // 复制按钮动画效果
        const originalText = base64CopyBtn.innerHTML;
        base64CopyBtn.innerHTML = '<i class="fa fa-check mr-2"></i>已复制';
        setTimeout(() => {
          base64CopyBtn.innerHTML = originalText;
        }, 2000);
      });

      // 下载Base64结果
      base64DownloadBtn.addEventListener("click", () => {
        if (!base64Output.value) return;

        const blob = dataURLtoBlob(base64Output.value);
        const url = URL.createObjectURL(blob);

        const a = document.createElement("a");
        a.href = url;
        a.download = `${selectedFile.name.split(".")[0]}.txt`;
        document.body.appendChild(a);
        a.click();

        setTimeout(() => {
          document.body.removeChild(a);
          URL.revokeObjectURL(url);
        }, 0);

        showStatus("Base64文件已开始下载！", "success");
      });

      // Blob上传相关
      blobUploadBtn.addEventListener("click", () => {
        if (!selectedFile) return;

        blobUploadBtn.disabled = true;
        blobProgressContainer.style.display = "block";
        blobStatus.textContent = "准备上传...";
        blobStatus.className = "status-message status-info";

        const chunkSize = parseInt(chunkSizeSelector.value) * 1024 * 1024; // MB转字节
        const totalChunks = Math.ceil(selectedFile.size / chunkSize);
        let uploadedChunks = 0;

        // 模拟上传过程
        const uploadChunks = async () => {
          for (let i = 0; i < totalChunks; i++) {
            const start = i * chunkSize;
            const end = Math.min(start + chunkSize, selectedFile.size);
            const chunk = selectedFile.slice(start, end);

            // 模拟上传每个分片
            await simulateChunkUpload(chunk, i, totalChunks);

            // 更新进度
            uploadedChunks++;
            const percentComplete = Math.round(
              (uploadedChunks / totalChunks) * 100
            );
            blobProgressBar.style.width = percentComplete + "%";
            blobProgressBar.textContent = `${percentComplete}% (${uploadedChunks}/${totalChunks})`;
          }

          // 所有分片上传完成
          setTimeout(() => {
            blobProgressContainer.style.display = "none";
            blobStatus.textContent = "上传完成！";
            blobStatus.className = "status-message status-success";

            // 生成模拟URL
            const mockUrl = `https://example.com/uploads/${selectedFile.name}`;
            blobOutput.value = mockUrl;
            blobUrlCopyBtn.disabled = false;

            showStatus("视频已成功上传！", "success");
            blobUploadBtn.disabled = false;
          }, 500);
        };

        uploadChunks().catch((error) => {
          console.error("上传失败:", error);
          blobStatus.textContent = "上传失败，请重试";
          blobStatus.className = "status-message status-error";
          blobProgressContainer.style.display = "none";
          blobUploadBtn.disabled = false;
        });
      });

      // 复制Blob URL
      blobUrlCopyBtn.addEventListener("click", () => {
        if (!blobOutput.value) return;

        blobOutput.select();
        document.execCommand("copy");

        showStatus("视频URL已复制到剪贴板！", "success");

        // 复制按钮动画效果
        const originalText = blobUrlCopyBtn.innerHTML;
        blobUrlCopyBtn.innerHTML = '<i class="fa fa-check mr-2"></i>已复制';
        setTimeout(() => {
          blobUrlCopyBtn.innerHTML = originalText;
        }, 2000);
      });

      // 模拟分片上传
      function simulateChunkUpload(chunk, chunkIndex, totalChunks) {
        return new Promise((resolve) => {
          // 模拟上传延迟
          const delay = Math.random() * 500 + 300;

          // 更新状态
          blobStatus.textContent = `正在上传分片 ${
            chunkIndex + 1
          }/${totalChunks}...`;

          setTimeout(() => {
            resolve();
          }, delay);
        });
      }

      // 辅助函数：将DataURL转换为Blob
      function dataURLtoBlob(dataurl) {
        const arr = dataurl.split(",");
        const mime = arr[0].match(/:(.*?);/)[1];
        const bstr = atob(arr[1]);
        let n = bstr.length;
        const u8arr = new Uint8Array(n);

        while (n--) {
          u8arr[n] = bstr.charCodeAt(n);
        }

        return new Blob([u8arr], { type: mime });
      }

      // 显示状态消息
      function showStatus(message, type) {
        statusMessage.textContent = message;
        statusMessage.className = "status-message";

        if (type === "success") {
          statusMessage.classList.add("status-success");
        } else if (type === "error") {
          statusMessage.classList.add("status-error");
        } else if (type === "info") {
          statusMessage.classList.add("status-info");
        }

        // 5秒后自动隐藏消息
        setTimeout(() => {
          statusMessage.textContent = "";
          statusMessage.className = "status-message";
        }, 5000);
      }

      // 重置UI状态
      function resetUI() {
        preview.src = "";
        base64Output.value = "";
        blobOutput.value = "";

        // 禁用处理按钮
        base64ConvertBtn.disabled = true;
        base64CopyBtn.disabled = true;
        base64DownloadBtn.disabled = true;
        blobUploadBtn.disabled = true;
        blobUrlCopyBtn.disabled = true;

        // 隐藏进度条
        base64ProgressContainer.style.display = "none";
        base64ProgressBar.style.width = "0%";
        base64ProgressBar.textContent = "0%";
        blobProgressContainer.style.display = "none";
        blobProgressBar.style.width = "0%";
        blobProgressBar.textContent = "0%";

        // 重置状态消息
        showStatus("", "");
        blobStatus.textContent = "";
        blobStatus.className = "status-message";

        // 重置文件信息
        fileName.textContent = "-";
        fileSize.textContent = "-";
        fileType.textContent = "-";
      }
    </script>
  </body>
</html>
